<?php

namespace backend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\web\IdentityInterface;
use common\models\AR;

/**
 * AdminUser model
 *
 * @property integer $id
 * @property string $name
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $role
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $password write-only password
 */
class AdminUser extends AR implements IdentityInterface {

    const STATUS_LOCKON = 0;
    const STATUS_ACTIVE = 1;
    const TYPE_PLATFROM = 1;
    const TYPE_SUPPLIER = 2;
    const TYPE_DELIVERY = 3;

    public $modelName = '管理员';

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            TimestampBehavior::className(),
        ];
    }

    public static function tableName() {
        return '{{%admin_user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['add_time', 'last_login_time', 'role_id', 'type', 'type_id', 'is_root'], 'integer'],
            [['action_list'], 'string'],
            [['name'], 'string', 'max' => 60],
            [['email', 'password_hash'], 'string', 'max' => 45],
            [['last_login_ip'], 'string', 'max' => 15],
            [['name'], 'unique']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '用户名',
            'email' => '邮箱',
            'password_hash' => 'md5后的密码',
            'add_time' => '添加时间',
            'last_login_time' => '最后登录时间',
            'last_login_ip' => '最后登录IP',
            'action_list' => 'Action List',
            'role_id' => '所属角色',
            'is_root' => '是否为子系统的根管理员',
            'is_platform' => '平台帐户',
            'supplier_id' => '所属供应商',
            'delivery_id' => '所属配送中心',
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id) {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null) {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by name
     *
     * @param string $name
     * @return static|null
     */
    public static function findByUsername($name) {
        return static::findOne(['name' => $name, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token) {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
                    'password_reset_token' => $token,
                    'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token) {
        if (empty($token)) {
            return false;
        }
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId() {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey() {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password) {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password) {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey() {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken() {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken() {
        $this->password_reset_token = null;
    }

    /**
     * 返回管理员帐户所属系统
     * @return boolean|int 1平台 2 供应商 3配送中心
     */
    public function getType() {
        if ($this->is_platform) {
            return self::TYPE_PLATFROM;
        } else {
            if ($this->supplier_id > 0) {
                return self::TYPE_SUPPLIER;
            }

            if ($this->delivery_id > 0) {
                return self::TYPE_DELIVERY;
            }
        }
        return FALSE;
    }

    /**
     * 根据帐户所属平台，返回菜列表
     * @return null|array
     */
    public function getMenu() {
        $menu = Yii::$app->params['menu'];
        $type = $this->currentSystem;
        if ($type !== FALSE && array_key_exists($type, $menu)) {
            return $menu[$type];
        } else {
            return null;
        }
    }

    /**
     * 获取当前账户能登录的系统
     * @return array 
     */
    public function getSystems() {
        $sys = [];

        $this->is_platform && $sys[] = AdminUser::TYPE_PLATFROM;
        $this->supplier_id > 0 && $sys[] = AdminUser::TYPE_SUPPLIER;
        $this->delivery_id > 0 && $sys[] = AdminUser::TYPE_DELIVERY;
        return $sys;
    }

    /**
     * 获取当前登录系统类型
     * @return boolean
     */
    public function getCurrentSystem() {
        $systems = $this->getSystems();
        if (empty($systems)) {
            return false;
        }
        $cookieName = 'u_' . $this->id . '_sys';
        $sysId = \Yii::$app->getRequest()->getCookies()->getValue($cookieName);

        if ($sysId && in_array($sysId, $systems)) {
            return $sysId;
        } else {
            return $systems[0];
        }
    }

    /**
     * 设置当前登录系统类型
     * @param type $systemId
     * @return boolean
     */
    public function setCurrentSystem($systemId) {
        $systems = $this->getSystems();
        if (!in_array($systemId, $systems)) {
            return false;
        }

        $cookieName = 'u_' . $this->id . '_sys';
        $cookie = new \yii\web\Cookie([
            'name' => $cookieName,
            'value' => $systemId,
            'expire' => time() + 86400 * 365,
        ]);
        \Yii::$app->getResponse()->getCookies()->add($cookie);
    }

}
